package com.xiaoyu.lanling.feature.conversation.date

import `in`.srain.cube.concurrent.AppThreads
import `in`.srain.cube.request.JsonData
import `in`.srain.cube.util.log.LogEvent
import com.xiaoyu.base.entity.ConversationEntity
import com.xiaoyu.base.utils.ListUtil
import com.xiaoyu.im.provider.ConversationManager
import com.xiaoyu.lanling.event.conversation.ConversationListUpdateEvent
import com.xiaoyu.lanling.feature.conversation.model.ConversationListItemBase
import com.xiaoyu.lanling.feature.conversation.model.MainConversationItem
import com.xiaoyu.lanling.feature.newtips.data.NewTipData
import com.xiaoyu.lanling.log.AppLogClient
import java.util.*

class ConversationListData {

    companion object {
        val instance by lazy { ConversationListData() }
    }

    val list = Collections.synchronizedList<ConversationListItemBase>(mutableListOf())

    fun loadAllConversation() {
        AppThreads.runOnDBThread {
            ConversationManager.getInstance().updateConversationList()
        }
    }

    fun onHomeListUpdate() {
        val conversationList = buildConversationList()

        synchronized(list) {
            list.clear()
            list.addAll(conversationList)
            try {
                list.sort()
            } catch (e: Exception) {
                e.printStackTrace()
            }
        }
        ConversationListUpdateEvent().post()
        refreshMainChatCount()
    }

    private fun refreshMainChatCount() {
        var newTipCount = 0
        synchronized(list) {
            val logEvent = LogEvent("refresh_main_chat_count")
            val data = mutableListOf<JsonData>()
            for (itemBase in list) {
                if (itemBase == null) {
                    continue
                }
                newTipCount += itemBase.newTipCount

                if (itemBase is MainConversationItem) {
                    val conversationJson = JsonData.newMap()
                    conversationJson.put("uid", itemBase.user.uid)
                    conversationJson.put("name", itemBase.user.name)
                    conversationJson.put("unreadCount", itemBase.newTipCount)
                    data.add(conversationJson)
                }
            }
            logEvent.putData("conversationsData", data)
            AppLogClient.instance.addLog(logEvent)
        }
        NewTipData.instance.updateMainChatCount(newTipCount)
    }

    private fun buildConversationList(): List<MainConversationItem> {
        val entities: List<ConversationEntity> = ConversationManager.getInstance().buildDisplayConversationList()
        return ListUtil.convertToList(entities) { entity -> MainConversationItem(entity) }
    }
}